package com.power.strategy.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.power.contant.AuthConstants;
import com.power.domain.SysUserLogin;
import com.power.mapper.SysUserLoginMapper;
import com.power.model.SecurityUser;
import com.power.strategy.LoginStrategy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

@Service(AuthConstants.SYS_USER_LOGIN)
public class SysLoginStrategy implements LoginStrategy {

    @Resource
    private SysUserLoginMapper sysUserLoginMapper;

    /**
     * 前端是通过系统的用户名和密码换取token的
     *
     * @param username SpringSecurity框架中用户的唯一标识
     * @return
     */
    @Override
    public UserDetails realLogin(String username) {
        //查询用户的名称
        SysUserLogin sysUserLogin = sysUserLoginMapper.selectOne(new QueryWrapper<SysUserLogin>().eq("username", username));

        if (ObjectUtil.isNotNull(sysUserLogin)) {
            //查询权限操作  在数据库中查询的时候需要去重  通过使用set 避免使用了DISTINCT关键字
            Set<String> perms = sysUserLoginMapper.selectPermsByUserId(sysUserLogin.getUserId());

            //将返回的对象放到容器的上下文中
            //创建项目的安全认证框架
            SecurityUser securityUser = new SecurityUser();
            securityUser.setUserId(sysUserLogin.getUserId());
            securityUser.setUsername(sysUserLogin.getUsername());
            securityUser.setPassword(sysUserLogin.getPassword());
            securityUser.setStatus(sysUserLogin.getStatus());
            securityUser.setLoginType(AuthConstants.SYS_USER_LOGIN);
            securityUser.setShopId(sysUserLogin.getShopId());
            //判断用户权限是否有值(判断集合一般要有两个条件)
            if (CollectionUtil.isNotEmpty(perms) && perms.size() != 0) {
                securityUser.setPerms(perms);//重写了set方法
            }
            return securityUser;
        }
        return null;
    }
}
